#!/bin/bash

# set -ux

#变量
nodes=(server160 server161 server162)

echo '配置ssh免密'
if [ -f "/root/.ssh" ]; then
  echo "/root/.ssh exist"
else
  echo "/root/.ssh does not exist"
  ssh-keygen -t rsa
  cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
fi

echo '配置java'
mkdir -p /usr/local/java &&
  tar -zxf res/Alibaba_Dragonwell_8.10.11_x64_linux.tar.gz -C /usr/local/java

echo '配置zookeeper'
tar -zxf res/apache-zookeeper-3.8.0-bin.tar.gz &&
  mv apache-zookeeper-3.8.0-bin /home/zookeeper &&
  mkdir -pv /home/zookeeper/{data,logs} &&
  cp /home/zookeeper/conf/zoo_sample.cfg /home/zookeeper/conf/zoo.cfg

# 默认id
echo 1 > /home/zookeeper/data/myid

sed -i "/^dataDir=/c dataDir=/home/zookeeper/data"  /home/zookeeper/conf/zoo.cfg

cat >> /home/zookeeper/conf/zoo.cfg << EOF
dataLogDir=/home/zookeeper/logs
# server cluster
server.1=server160:2888:3888
server.2=server161:2888:3888
server.3=server162:2888:3888
EOF

cat /home/zookeeper/conf/zoo.cfg | grep -v '^#' | grep -v '^$'

echo '配置kafka'
tar -zxf res/kafka_2.13-3.1.0.tgz &&
  mv kafka_2.13-3.1.0 /home/kafka &&
  mkdir -pv /home/kafka/logs

zoos=""
for ((i = 0; i < ${#nodes[@]}; i++)); do
  zoos="$zoos${nodes[i]}:2181,"
done

# 去除末尾的,
zoos="${zoos/%,/}"

# 修改配置文件
sed -i -e "/^broker.id=/c broker.id=1" \
  -e "/^log.dirs=/c log.dirs=/home/kafka/logs" \
  -e "/^zookeeper.connect=/c zookeeper.connect=$zoos" \
  /home/kafka/config/server.properties

cat /home/kafka/config/server.properties | grep -v '^#' | grep -v '^$'

echo '配置环境变量'
cat >> ~/.bashrc << EOF
# java env
export JAVA_HOME=/usr/local/java/dragonwell-8.10.11
export PATH=\$PATH:\$JAVA_HOME/bin
# zookeeper env
export ZOOKEEPER_HOME=/home/zookeeper
export PATH=\$PATH:\$ZOOKEEPER_HOME/bin
# kafka env
export KAFKA_HOME=/home/kafka
export PATH=\$PATH:\$KAFKA_HOME/bin
EOF

cat ~/.bashrc | grep -v '^#' | grep -v '^$'
